import sys
import pygame
import screen
import title_screen

class HighScoreScreen(screen.Screen):
    pygame.font.init()
    FONT = pygame.font.Font(None, 20)
    
    def __init__(self):
        screen.Screen.__init__(self)
        self.highscore_screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT), pygame.DOUBLEBUF|pygame.HWSURFACE)
        self.high_scores = []
        scores_file = open('../res/highscores/high.scores', 'r')
        for line in scores_file:
            name, score = line.split()
            self.high_scores.append((score, name))
        self.interval = 0.1
        
    def render(self):
        self.highscore_screen.fill((72, 75, 12))
        surf = self.FONT.render("High Score", True, (255, 255, 255))
        self.highscore_screen.blit(surf, (self.WIDTH/2 - surf.get_width()/2, self.HEIGHT/5))
        entry_count = 1
        for entry in sorted(self.high_scores, None, None, True):
            entry_count += 1
            score, name = entry
            surf = self.FONT.render(name, True, (255, 255, 255))
            self.highscore_screen.blit(surf, (2 * self.WIDTH / 5, self.HEIGHT/5 + entry_count * surf.get_height()))
            surf = self.FONT.render(score, True, (255, 255, 255))
            self.highscore_screen.blit(surf, (3 * self.WIDTH / 5, self.HEIGHT/5 + entry_count * surf.get_height()))


    def update(self, time):
        #TODO fill in update implementation
        pass

    def process_events(self, change_state):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                elif event.key == pygame.K_RETURN:
                    change_state(title_screen.TitleScreen())

